package com.pirestupppai.widgets.dialog;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.view.Gravity;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.pirestupppai.R;
import com.pirestupppai.common.Constant;

/**
 * 录制倒计时
 *
 * author: xiaoluo
 * date: 2017/5/26 10:15
 */
public class CountDownDialog extends Dialog{
    private Context mContext;

    private ImageView mCountImg;
    private RelativeLayout mCountLayout;
    private static final int MSG_COUNT = 100;
    private int count = 0;
    private OnDismissListener mListener;
    private CountDownDialog dialog = this;

    private int[] images = {R.drawable.ic_three, R.drawable.ic_two, R.drawable.ic_one};

    public CountDownDialog(@NonNull Context context, DialogInterface.OnDismissListener listener) {
        super(context, R.style.VideoDialog);
        mContext = context;
        mListener = listener;
        setContentView(R.layout.dialog_count_down);

        mCountLayout = (RelativeLayout) findViewById(R.id.count_layout);
        mCountImg = (ImageView) findViewById(R.id.count_img);

        Window window = this.getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = Constant.WIDTH_OF_SCREEN;
        lp.height = Constant.HEIGHT_OF_SCREEN;
        window.setAttributes(lp);
        window.setGravity(Gravity.CENTER_HORIZONTAL);
        setCancelable(false);

        LinearLayout.LayoutParams countLp = (LinearLayout.LayoutParams) mCountLayout.getLayoutParams();
        countLp.topMargin = Constant.WIDTH_OF_SCREEN / 2 + Constant.HEIGHT_OF_STATUSBAR;
        mCountLayout.setLayoutParams(countLp);

        mHandler.sendEmptyMessage(MSG_COUNT);

    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_COUNT:
                    if (count <= 2) {
                        mCountImg.setImageResource(images[count]);
                        count ++;
                        mHandler.sendEmptyMessageDelayed(MSG_COUNT, 1000);
                    } else {
                        dismiss();
                        mListener.onDismiss(dialog);
                    }

            }
        }
    };

}
